#!/usr/bin/env ruby

require "faster_csv"

class RedBook::Logger

	# Initialize CSV Plugin hooks. <i>[CSV Plugin]</i>
	def initialize_csv
	
		@hooks.add :sort_config_header do |args|
			args[:scfg][:csv] = {:info => 'CSV Settings'}
			false
		end
		
		@hooks.add :sort_config_match do |args|
			if args[:index].to_s =~ /^csv_/ && args[:scfg][:csv] then
				args[:scfg][:csv] << { args[:index] => args[:value], :_attributes => {:raw => true}}
				true
			end
		end
		
		@hooks.add :save_file do |args|
			if args[:type] == 'csv' then
				sep = @@config[:csv_separator] || ','
				if @@config[:csv_msproject_fields] then
					h_type = 'Item Type'
					h_value = 'Value'
					h_message = 'Name'
					h_start_date = 'Start'
					h_end_date = 'Finish'
					h_duration = 'Activity Duration'
					h_tags = 'Notes'
				else
					time_unit = @@config[:csv_duration_time_unit] ? @@config[:csv_duration_time_unit] : 'seconds'
					h_type = (@@config[:csv_header_type] || 'Item Type')
					h_value = (@@config[:csv_header_value] || 'Value')
					h_message = (@@config[:csv_header_message] || 'Message')
					h_start_date = (@@config[:csv_header_start_date] || 'Start Date')
					h_end_date = (@@config[:csv_header_end_date] || 'End Date')
					h_duration = (@@config[:csv_header_duration] || "Duration (#{time_unit})")
					h_tags = (@@config[:csv_header_tags] || 'Tags')
				end
				csv_str = FasterCSV.generate(:col_sep => sep) do |csv|
					csv << [h_type, h_value, h_message, h_start_date, h_end_date, h_duration, h_tags]
					args[:output].each { |l| csv << l}
				end
				write_file(csv_str, args[:file])
				true
			else
				false
			end
		end
		
	end
	
end


